import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {BaseService} from "../../../shared/service/base.service";
import {ApiUrl} from "../../../config/api-url";
import {Globals} from "../../../globals";
import {MyDateModel} from "../../../models/my-date.model";
import {NzUploadFile} from "ng-zorro-antd/upload";
import {validMoney} from "../../../shared/validator/validator";
import {MenuTabsService} from "../../../layout/menu-tabs.service";
import {AppReuseStrategy} from "../../../layout/app-reuse-strategy";
import {Consts} from "../../../config/consts";
import {RoleIdEnum} from "../../../enums/role-id.enum";

@Component({
  selector: 'app-withdrawals-edit',
  templateUrl: './withdrawals-edit.component.html',
  styleUrls: ['./withdrawals-edit.component.less']
})
export class WithdrawalsEditComponent implements OnInit {
  // 加载状态
  isSpinning: boolean;
  isMobile = Globals.isMobile();
  // 提现类型
  withdrawType: any = '1';
  formModel: FormGroup;
  // 银行账户户名
  bankCertName: string;
  // 银行卡号
  bankCardNo: string;
  // 银行名称
  bankName: string;
  // 支行名称
  branchName: string;
  // 用户结算卡信息
  userBankCardList: any;
  // 平台扣除税点
  platformTax: number = 0;
  //开发票标识   01代开发票  02自开发票
  invoiceFlag: string;
  // 绑定银行卡类型
  cardNoType: number;
  isVisible: boolean;
  // 图片上传地址
  uploadUrl = ApiUrl.FileUrl + "/uploadImage";
  accessToken = 'bearer ' + sessionStorage.getItem(Consts.ACCESS_TOKEN);
  // 图片集合
  invoicePhotoList = [];
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
    MERCHANT: RoleIdEnum.MERCHANT,
  };
  // 角色
  roleId: number;
  // 平台收款余额
  balance: number;
  // 分润余额
  commissionBalance: number;
  serverFileUrl: any;

  previewVisible = false;
  previewImage: string

  constructor(private activatedRoute: ActivatedRoute,
              private fb: FormBuilder,
              public baseService: BaseService,
              private menuTabsService: MenuTabsService,
              private router: Router) {
    this.buildForm();
    this.activatedRoute.queryParams.subscribe(params => {
      this.findUserBankCardList();
    });
  }

  ngOnInit(): void {
    this.findBackEndUrl();
    this.roleId = JSON.parse(sessionStorage.getItem(Consts.USER_INFO)).roleId;
    if(this.roleId == this.roleIdEnum.MERCHANT){
      this.formModel.get('withdrawType').setValue('1');
      this.withdrawType = '1';
    }else{
      this.formModel.get('withdrawType').setValue('2');
      this.withdrawType = '2';
    }
  }

  buildForm() {
    this.formModel = this.fb.group({
      withdrawType: ['1', [Validators.required]],
      invoiceFlag: ['', [Validators.required]],
      balance: ['0', [Validators.required]],
      money: [null, [validMoney]],
      tax: ['0', []],
      actualAccount: ['0', []],
      invoiceMoney: ['0', []],
      expressNo: ['', []],
      expressName: ['', []],
      invoiceDate: ['', []],
      invoicePhotoList: ['', []],
      type: ['', []],
    });
  }

  // 提交申请提现
  submitForm() {
    this.isSpinning = true;
    for (const i in this.formModel.controls) {
      if (!this.formModel.controls[i].valid) {
        this.isSpinning = false;
      }
      this.formModel.controls[i].markAsDirty();
      this.formModel.controls[i].updateValueAndValidity();
    }

    if (!this.isSpinning) {
      return;
    }
    // console.log(this.formModel.get('money').value)
    // if (this.formModel.get('money').value <= 0) {
    //   this.baseService.layer.modalInfo('请输入提现金额,并且不可以为负数或字符');
    //   this.isSpinning = false;
    //   return;
    // }
    if (this.formModel.get('money').value < 10) {
      this.baseService.layer.modalInfo('提现金额不能低于10元');
      this.isSpinning = false;
      return;
    }
    if (this.formModel.get('money').value < parseFloat(this.formModel.get('tax').value)) {
      this.baseService.layer.modalInfo('提现金额不能低于税费');
      this.isSpinning = false;
      return;
    }
    if (this.invoiceFlag == '02' && (this.formModel.get('invoiceDate').value == null || this.formModel.get('invoiceDate').value == '')) {
      this.baseService.layer.modalInfo('请填写开票日期')
      this.isSpinning = false;
      return;
    }
    if (this.formModel.get('money').value > this.formModel.get('balance').value) {
      this.baseService.layer.modalInfo('提现金额比余额大，不可提现');
      this.isSpinning = false;
      return;
    } else if (this.invoiceFlag == '02' && (this.formModel.get('expressNo').value == null || this.formModel.get('expressNo').value == ''
      || this.formModel.get('expressName').value == null || this.formModel.get('expressName').value == '')) {
      this.baseService.layer.modalInfo('请填写快递编号|快递公司名');
      this.isSpinning = false;
      return;
    }

    if (this.invoiceFlag == '02' && (this.invoicePhotoList.length <= 0)) {
      this.baseService.layer.modalInfo('请添加发票图片');
      this.isSpinning = false;
      return;
    }
    this.baseService.layer.modalConfirm('你是否确定提交', confirm => {
      if (confirm) {
        this.formModel.get('invoicePhotoList').setValue(this.invoicePhotoList);
        this.baseService.post(ApiUrl.MoneyWithdrawUrl, this.formModel.value).subscribe(data => {
          if (data.status == 0) {
            this.isSpinning = false;
            let url = '/withdrawals/withdrawals-edit'
            console.log(url)
            this.menuTabsService.menuList = this.menuTabsService.menuList.filter(p => p.module !== url);
            AppReuseStrategy.deleteRouteSnapshot(url);
            this.router.navigateByUrl('/withdrawals/withdrawals-list?r=1');
          } else {
            this.baseService.layer.messageError(data.msg);
            this.isSpinning = false;
          }
        });
      }else{
        this.isSpinning = false;
      }
    });
  }

  findBackEndUrl() {
    this.baseService.get(ApiUrl.Config + '/findBackEndUrl?type=image').subscribe(
      data => {
        if (data.status == 0) {
          if (data.data == null || data.data.url == null) {
            this.baseService.layer.messageError('找不到地址');
            return;
          }
          this.serverFileUrl = data.data.url;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }



  // 键盘输入提现余额 计算税费和发票金额
  checkMoney() {
      if (this.formModel.get('invoiceFlag').value == '01') {
        if (this.formModel.get('money').value != null && this.formModel.get('money').value != '') {
          // tslint:disable-next-line:radix
          this.formModel.get('tax').setValue(((this.formModel.get('money').value * this.platformTax)).toFixed(2));
          // tslint:disable-next-line:radix
          this.formModel.get('actualAccount').setValue((Number(this.formModel.get('money').value) - Number(this.formModel.get('tax').value)).toFixed(2));
        }
      } else {
        if (this.formModel.get('money').value != null && this.formModel.get('money').value != '') {
          // tslint:disable-next-line:radix
          this.formModel.get('tax').setValue(((this.formModel.get('money').value * 0.03)).toFixed(2));
          // tslint:disable-next-line:radix
          this.formModel.get('invoiceMoney').setValue((Number(this.formModel.get('money').value) - Number(this.formModel.get('tax').value)).toFixed(2));
        }
      }
  }

  // 选择提现对私或对公类型
  clickInvoiceFlag(event) {
    let checkBankCard = false;
    let title = null;
    if (event == 1) {
      title = '你还没绑定对私银行卡,是否绑定';
      this.cardNoType = 1;
      this.userBankCardList.forEach(bankCard => {
        if (bankCard.type == 1) {
          checkBankCard = true;
          this.getWithdrawalsInit(bankCard);
        }
      });
    } else {
      title = '你还没绑定对公银行卡,是否绑定';
      this.cardNoType = 2;
      this.userBankCardList.forEach(bankCard => {
        if (bankCard.type == 2) {
          checkBankCard = true;
          this.getWithdrawalsInit(bankCard);
        }
      });
    }

    if (!checkBankCard) {
      this.baseService.layer.modalConfirm(title, confirm => {
        if (confirm) {
          this.isVisible = true;
        }
        if (event == 1) {
          this.invoiceFlag = '02';
          this.formModel.get('invoiceFlag').setValue('02');
        } else {
          this.invoiceFlag = '01';
          this.formModel.get('invoiceFlag').setValue('01');
        }
      });
    }
  }

// 查询用户的银行卡信息
  findUserBankCardList() {
    this.baseService.get(ApiUrl.UserBankCardUrl + '/findUserBankCardList').subscribe(data => {
      this.userBankCardList = data.data;
      // 判断运营商默认显示余额提现， 机构进入显示分润提现
      if (this.cardNoType == null) {
        this.getWithdrawalsInit(this.userBankCardList[0]);
      } else {
        this.userBankCardList.forEach(bankCard => {
          if (this.cardNoType == bankCard.type) {
            this.getWithdrawalsInit(bankCard);
          }
        });
      }

      // data.data.forEach(bankCard => {
      //   console.log(bankCard)
      //   if(bankCard.type == 1){
      //     this.bankCertName = bankCard.bankCertName;
      //     this.bankCardNo = bankCard.bankCardNo;
      //     this.bankName = bankCard.bankName;
      //     this.branchName = bankCard.branchName;
      //     this.formModel.get("invoiceFlag").setValue(bankCard.type);
      //   }
      // });
    });
  }

  //  获取提现信息
  getWithdrawalsInit(bankCard) {
    this.bankCertName = bankCard.bankCertName;
    this.bankCardNo = bankCard.bankCardNo;
    this.bankName = bankCard.bankName;
    this.branchName = bankCard.branchName;
    this.formModel.get('type').setValue(bankCard.type);
    console.log(bankCard.bankCertName)
    // 提现类型
    if (bankCard.type == 1) {
      this.formModel.get('invoiceFlag').setValue('01');
      this.invoiceFlag = '01';
    } else {
      this.formModel.get('invoiceFlag').setValue('02');
      this.invoiceFlag = '02';
    }
    // 可提现余额
    if (this.formModel.get('withdrawType').value == '1') {
      this.formModel.get('balance').setValue(bankCard.balance);
    } else {
      this.formModel.get('balance').setValue(bankCard.commissionBalance);
    }
    // 获取余额
    this.balance = bankCard.balance;
    this.commissionBalance = bankCard.commissionBalance;
    // 平台扣除税点
    if (bankCard.withdrawRate) {
      this.platformTax = bankCard.withdrawRate.toFixed(2);
    } else {
      this.platformTax = 0.08;
    }
    this.checkMoney();
  }

  clickWithdrawalsType(event) {
    if (event == 1) {
      this.formModel.get('balance').setValue(this.balance);
    } else {
      this.formModel.get('balance').setValue(this.commissionBalance);
    }
  }



  emitBindBankCard($event: any) {
    this.isVisible = $event;
    this.findUserBankCardList();
  }

  handleChange(info): void {
    switch (info.file.status) {
      case 'uploading':
        break;
      case 'done':
        // tslint:disable-next-line:no-non-null-assertion
        this.getBase64(info.file!.originFileObj!, (img: string) => {
          console.log(info)
          let value = info.file.response.data.keyRes;
          value = value.substring(0, value.lastIndexOf('.'));
          this.invoicePhotoList.push(value);
        });
        break;
      case 'error':
        this.baseService.layer.messageError('网络错误!稍后重试!');
        break;
    }
  }

  // 转换64位
  private getBase64(img: File, callback: (img: string) => void) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result!.toString()));
      reader.readAsDataURL(img);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }


  // 压缩图片
  transformFile = (file: NzUploadFile) => {
    return this.baseService.zorro.imgUpload(file);
  }
  // 查看图片
  // viewImg = async (file) => {
  //   console.log("是否进入")
  //   this.previewVisible = true;
  //   this.previewImage = ApiUrl.ServerFileUrl + file.response.data.keyRes;
  // }
  handlePreview = async (file: NzUploadFile) => {
    window.open(this.serverFileUrl + file.response.data.keyRes);
  };
  nzDownload = async (file) => {
    window.open(this.serverFileUrl + file.response.data.keyRes);
  }

  removeImg = async (file) => {
    let value = file.response.data.keyRes;
    value = value.substring(0, value.lastIndexOf('.'));
    for (let i = 0; i < this.invoicePhotoList.length; i++) {
      if (this.invoicePhotoList[i] == value) {
        this.invoicePhotoList.splice(i, 1);
      }
    }
  }


  onStartChange($event: any) {

  }

}
